package com.cloud.fim.protocol.serialize;

import com.cloud.fim.common.Serializer;
import com.cloud.fim.common.util.SingletonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 */
public class SerializerFactory {

    private static Map<Byte,Class<? extends Serializer>> maps = new ConcurrentHashMap<>();
    private static List<Class<? extends Serializer>> serializers = new ArrayList<>();

    static {
        synchronized(SerializerFactory.class){
            serializers.add(FastJsonSerializer.class);
            serializers.add(HessianSerializer.class);
            serializers.add(JdkSerializer.class);
            serializers.add(KryoSerializer.class);
            serializers.add(ProtoStuffSerializer.class);
            initSerializer();
        }
    }

    private SerializerFactory() {

    }

    private static void initSerializer() {
        List<Class<? extends Serializer>> serializers = new ArrayList<>();
        serializers = SerializerFactory.serializers;
        // filter did not flag the @BindAndEnableSerializer
        // filter the BindAndEnableSerializer enable set false
        serializers
                .stream()
                .filter(aClass -> {
                    BindAndEnableSerializer annotation = aClass.getAnnotation(BindAndEnableSerializer.class);
                    return annotation != null && annotation.enable();
                })
                .forEach(aClass -> {
                    BindAndEnableSerializer annotation = aClass.getAnnotation(BindAndEnableSerializer.class);
                    maps.put(annotation.name(),aClass);
                });
    }

    /**
     *
     * @param serializerType
     * @return
     */
   public static Serializer getSerializer(byte serializerType) {
       Class<? extends Serializer> aClass = SerializerFactory.maps.get(serializerType);
       if(aClass==null){
           return null;
       }
       return SingletonUtil.get(aClass);
    }

}
